//
//  YTOrderListViewModel.m
//  YiTuDriverClient
//
//  Created by 石少庸 on 2017/4/28.
//  Copyright © 2017年 Yitu. All rights reserved.
//

#import "YTOrderListViewModel.h"
#import "YTOrderServiceCityModel.h"
#import "YTOrderListModel.h"
#import "YTOrderServices.h"
#import "YTProfileModel.h"
#import "YTUserProfileServices.h"

#import <RongIMKit/RongIMKit.h>
#import <RongIMLib/RongIMLib.h>

@interface YTOrderListViewModel ()
@property (strong, nonatomic, readwrite) RACCommand *loadUserInfoCommand;
@property (strong, nonatomic, readwrite) RACCommand *checkOrderCommand;
@end

@implementation YTOrderListViewModel

- (void)initialize {
    _serviceCitys = [NSMutableArray array];
    _dataSource = [NSMutableArray array];
    
    [self loadData];
    [self changeTabClass];
    [self filterAndResetData];
    [self loadUserInfo];
    [self checkOrderState];
}

#pragma mark - tab切换

- (void)changeTabClass {
    @weakify(self);
    _changeTabCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSNumber *index) {
        @strongify(self);
        return [[RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            [self loadDataWithSubscriber:subscriber];
            return nil;
        }] initially:^{
            [self cleanData];
            self.tabClass = index.integerValue;
        }];
    }];
}

#pragma mark - 刷新和加载数据

- (void)loadData {
    // 刷新
    @weakify(self);
    self.requestRemoteDataCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSDictionary *input) {
        @strongify(self);
        return [[RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            [self loadDataWithSubscriber:subscriber];
            return nil;
        }] initially:^{
            [self cleanData];
        }];
    }];
    // 加载更多
    self.loadMoreDataCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSDictionary *input) {
        @strongify(self);
        return [[RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            [self loadDataWithSubscriber:subscriber];
            return nil;
        }] initially:^{
            self.page++;
        }];
    }];
}

#pragma mark - 筛选

- (void)filterAndResetData {
    @weakify(self);
    self.filterCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSDictionary *filterDict) {
        @strongify(self);
        return [[RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            [self loadDataWithSubscriber:subscriber];
            return nil;
        }] initially:^{
            [self cleanData];
            self.seatType = filterDict[@"seatType"];
            self.subType = filterDict[@"subType"];
            self.serviceCity = filterDict[@"serviceCity"];
            self.useTimeBegin = filterDict[@"useTimeBegin"];
            self.useTimeEnd = filterDict[@"useTimeEnd"];
        }];
    }];
}

#pragma mark - 加载用户信息

- (void)loadUserInfo {
    _loadUserInfoCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            [[YTUserProfileServices loadUserInfo] subscribeNext:^(NSDictionary *response) {
                if ([response[@"resultCode"] integerValue] == 1000) {
                    YTProfileModel *model = [YTProfileModel yy_modelWithJSON:response[@"responseData"]];
                    [YTUtilityManager manager].userModel = model;
                    [self connectedIMServerWithModel:model];
                    [subscriber sendNext:model];
                    [subscriber sendCompleted];
                }
            } error:^(NSError *error) {
                
            }];
            return nil;
        }];
    }];
}

- (void)connectedIMServerWithModel:(YTProfileModel *)model {
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:kRongYunToken];
    [[RCIM sharedRCIM] connectWithToken:token success:^(NSString *userId) {
        NSLog(@"***************IM连接成功***************");
    } error:^(RCConnectErrorCode status) {
        NSLog(@"***************IM连接失败***************");
    } tokenIncorrect:^{
        NSLog(@"***************IM token错误***************");
    }];
}

#pragma mark - 检测订单是否已经被抢

- (void)checkOrderState {
    @weakify(self);
    _checkOrderCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSString *order_id) {
        @strongify(self);
        self.order_id = order_id;
        return [YTOrderServices orderCheck:order_id];
    }];
}

#pragma mark - Private

- (void)loadDataWithSubscriber:(id<RACSubscriber>)subscriber {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"page"] = [NSString stringWithFormat:@"%zd", self.page];
    dict[@"tabClass"] = [NSString stringWithFormat:@"%zd", self.tabClass];
    dict[@"seatType"] = self.seatType;
    dict[@"subType"] = self.subType;
    dict[@"serviceCity"] = self.serviceCity;
    dict[@"useTimeBegin"] = self.useTimeBegin;
    dict[@"useTimeEnd"] = self.useTimeEnd;
    [[YTOrderServices loadOrderList:dict] subscribeNext:^(NSDictionary *response) {
        NSDictionary *data = response[@"responseData"];
        NSArray<YTOrderListModel *> *dataArray = [NSArray yy_modelArrayWithClass:[YTOrderListModel class] json:data[@"orderList"]];
        [self.dataSource addObjectsFromArray:dataArray];
        self.serviceCitys = [[NSArray yy_modelArrayWithClass:[YTOrderServiceCityModel class] json:data[@"serviceCity"]] mutableCopy];
        [subscriber sendNext:dataArray];
        [subscriber sendCompleted];
    }];
}

- (void)cleanData {
    self.page = 1;
    self.seatType = nil;
    self.subType = nil;
    self.serviceCity = nil;
    self.useTimeEnd = nil;
    self.useTimeEnd = nil;
    [self.dataSource removeAllObjects];
    [self.serviceCitys removeAllObjects];
}

@end
